'use strict';

const path = require('path')


const pkgDir = require('pkg-dir').sync;
const npmInstall = require('npminstall')
const pathExists = require('path-exists').sync // 查看目录是否在本地存在
const fsExtra = require('fs-extra') //在本地创建 指定目录

const { isObject } = require('@cjx-cli-dev/utils')
const formatPath =require('@cjx-cli-dev/format-path')
const { grtDefaultRegistry, getNpmLatestVersion } = require('@cjx-cli-dev/get-npm-info');
const log = require('@cjx-cli-dev/log')

class Package {
    // TODO
  constructor(options) {
    // console.log('Package', options)
    
    if (!options) {
      throw Error('Package类的options的参数必须有值')
    }
    if (!isObject(options)) {
      throw Error('Package类的options的参数必须是个对象')
    }
    // log.verbose('PackageOptions', options)

    // package 存储的目标路径
    this.targetPath = options.targetPath
    //缓存 package 的路径
    this.storeDir = options.storeDir
    // package 的name
    this.packageName = options.packageName
    // package 的version
    this.packageVersion = options.packageVersion

    // package 的缓存目录前缀
    this.cacheFilePathPrefix = this.packageName.replace('/', '+')

    // 是否用淘宝镜像下载 true/否   false/是
    this.isOriginal = options.isOriginal
    
  }

  async prepare() {
    if (this.storeDir && !pathExists(this.storeDir)) {
      // 如果缓存目录不存在 就创这个目录
      log.verbose('storeDir缓存目录不存在 正在创建这个目录')
      fsExtra.mkdirpSync(this.storeDir)
    }

    if (this.packageVersion === 'latest') {
      // 拿到最新版本
      this.packageVersion = await getNpmLatestVersion(this.packageName)
    }
    // log.verbose(`拿到最新版本packageVersion: ${this.packageVersion}`)
    // console.log('拿到最新版本packageVersion: ', this.packageVersion)
  }
  
  // init -> ../../node-modules/.store/@imooc-cli+init@1.1.3/node_modules/@imooc-cli/init
  // 获取package包的 缓存目录的路径
  get cacheFilePath() {
    return path.resolve(this.storeDir + '/.store', `${this.cacheFilePathPrefix}@${this.packageVersion}`)
  }

  // 获取缓存目录的package.json
  get cacheFilePathPackageJson() {
    return path.resolve(this.storeDir + '/.store', `${this.cacheFilePathPrefix}@${this.packageVersion}/node_modules/${this.packageName}`)
  }

  getSpecificCacheFilePath(packageVersion){
    return path.resolve(this.storeDir + '/.store', `${this.cacheFilePathPrefix}@${packageVersion}`)
  }

  // 判断当前Package 是否存在
  async exists() {
    if (this.storeDir) {
      // 缓存模式
      await this.prepare()
      console.log('缓存模式', this.cacheFilePath, pathExists(this.cacheFilePath))
      return pathExists(this.cacheFilePath)
    } else {
      // 判断 this.storeDir路径是否存在
      return pathExists(this.storeDir)
    }
  }

  // 安装Package
  install() {
    return npmInstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: grtDefaultRegistry(this.isOriginal),
      pkgs: [{name: this.packageName, version: this.packageVersion}]
    })
  }

  // 更新Package
  async update() {
    await this.prepare()
    // 获取最新的 npm 模块版本号
    const latestPackageVersion = await getNpmLatestVersion(this.packageName)
    // 查询最新版本号对应的路径是否存在
    const latestFilePath = this.getSpecificCacheFilePath(latestPackageVersion)
    // 如果不存在，则直接安装最新版本
    if (!pathExists(latestFilePath)) {
      await npmInstall({
        root: this.targetPath,
        storeDir: this.storeDir,
        registry: grtDefaultRegistry(this.isOriginal),
        pkgs: [{name: this.packageName, version: latestPackageVersion}]
      })
      log.verbose(`更新缓存里的 ${this.packageName} package包到最新版本`, latestPackageVersion)
      this.packageVersion = latestPackageVersion
    } else {
      log.verbose(`缓存里的 ${this.packageName} package包已经是最新的了`, latestPackageVersion)
      this.packageVersion = latestPackageVersion
    }
  }

  // 获取入口文件
  getRootFilePath() {
    // 1. 获取package.json所在目录 - pkg-dir
    // 2. 读取pack.json - require()
    // 3. main/lib -path
    // 4. 路径的兼容（macOS/windows)
    // console.log(111, dir, this.targetPath)
    function _getRootFile(targetPath) {
      const dir = pkgDir(targetPath)
      if (dir) {
        // const testPath = '/Users/xiejie/Desktop/code/脚手架/cjx-cli-dev/commands/init/package.json'
        // const pagFile = require(`${testPath}/package.json`)
        // const pkgFile = require(`/Users/xiejie/Desktop/code/脚手架/cjx-cli-dev/commands/init/package.json`)
        // const language = '/Users/xiejie/Desktop/code/脚手架/cjx-cli-dev/models/package/package'
        // import(/* webpackIgnore: false */ `${language}.json`).then((module) => {
        //   // do something with the translations
        //   console.log(222, module)
        // });
        // console.log(333, dir)
        const pkgFile = require(path.resolve(dir, 'package.json'))
        // console.log(444, pkgFile, path.resolve(dir, 'package.json'))
        if (pkgFile && pkgFile.main) {
          return formatPath(path.resolve(dir, pkgFile.main))
        }
       
        
      }
      return null
    }
    if (this.storeDir) {
      // console.log('缓存目录storeDir存在', this.storeDir, this.cacheFilePathPackageJson)
      // /Users/xiejie/.cjx-cli/dependencies/node_modules/.store/@imooc-cli+init@1.1.3/node_modules/@imooc-cli/init
      // console.log(require(path.resolve('/Users/xiejie/.cjx-cli/dependencies/node_modules/.store/@imooc-cli+init@1.1.3/node_modules/@imooc-cli/init', 'package.json')))
      return  _getRootFile(this.cacheFilePathPackageJson)
    } else {
      // 缓存目录不存在
      return  _getRootFile(this.targetPath)
    }
   
  }
}

module.exports = Package;
